import React, { PureComponent } from "react";
import { withRouter } from "react-router-dom";
import { Table, Button, Modal, Tabs, message } from "antd";
import classnames from "classnames";
import TransactionForm from "./TransactionForm";
import { stampToDate, fixedZero } from "../../utils";
import { IMAGES_ADDRESS, WS_PREFIX } from "../../utils/constants";
import ReconnectingWebSocket from "../../utils/ReconnectingWebSocket";
import PayModal from "./PayModal";
import PasswordPopup from "./PasswordModal";
import SettingPopup from "./SettingModal";
import TransfPopup from "../../components/transfPopup";

const TabPane = Tabs.TabPane;

class TradeContainer extends PureComponent {
  state = {
    coinVolume: 0,
    advertList: null,
    loadingAdvert: false,
    current: 1,
    pageSize: 10,
    selectedCoin: null,
    recordIndex: 0,
    releaseVisible: false,
    transactionVisible: false,
    myAdvertList: null,
    previewImage: "",
    appealList: null, //我的申诉
    appealPage: 1,
    appealTotal: 0,
    advertPage: 1, //我的广告列表page
    advertTotal: 0,
    completedPage: 1,
    completedTotal: 0,
    cancelPage: 1,
    cancelTotal: 0,
    undoOrderList: [],
    completedOrderList: [],
    cancelledOrderList: [],
    currentOrderTab: "undoOrder",
    payModal: "",
    appealModal: ""
  };

  request = window.request;

  componentWillReceiveProps(nextProps) {
    this.getAdvertList(1, nextProps);
  }

  componentWillMount() {
    this.getAdvertList(1);

    if (sessionStorage.getItem("account")) {
      this.getUndoOrderList();
    }

    // this.setState({ showAppeal: <PayModal /> });
  }

  componentDidMount() {
    //登录后才打开websockets
    if (JSON.parse(sessionStorage.getItem("account"))) {
      const userId = JSON.parse(sessionStorage.getItem("account")).id;
      this.offlineWS = new ReconnectingWebSocket(
        `${WS_PREFIX}/c2cUser?${userId}`
      );
      this.offlineWS.onopen = () => {
        if (this.offlineWS.readyState === 1) {
          this.offlineWS.send("ping");
        }
      };

      this.offlineInterval = setInterval(() => {
        if (this.offlineWS.readyState === 1) {
          this.offlineWS.send("ping");
        }
      }, 1000 * 10);

      this.offlineWS.onmessage = evt => {
        if (evt.data === "pong") {
          return;
        }
        const record = JSON.parse(evt.data);
        if (record.id) {
          let hasRecord = false;
          let undoOrderList = this.state.undoOrderList.map(item => {
            if (record.subOrderId === item.subOrderId) {
              record.key = record.id;
              // record.bankInfo = item.bankInfo;
              // record.askUserName = item.askUserName;
              hasRecord = true;
              return record;
            }
            return item;
          });
          if (!hasRecord) {
            record.key = record.id;
            undoOrderList.push(record);
          }
          undoOrderList = undoOrderList.filter(item => {
            return item.status === 0 || item.status === 1;
          });
          this.setState({ undoOrderList });
        }
      };
    }
  }

  componentWillUnmount() {
    if (this.orderInterval) {
      clearInterval(this.orderInterval);
    }
    clearInterval(this.offlineInterval);
    this.offlineWS && this.offlineWS.close();
  }

  pageOnChange = (page, pageSize) => {
    this.setState({ current: page });
    this.getAdvertList(page);
  };

  //根据币种和交易类型分页获取广告列表
  getAdvertList = (current, props = this.props) => {
    this.setState({ loadingAdvert: true });
    const { exType, coin } = props;
    const { pageSize } = this.state;
    const typeMap = {
      buy: 1,
      sell: 0
    };
    this.request("/offline/gadvert/list", {
      body: {
        exType: typeMap[exType],
        coinId: coin.coinId,
        currentPage: current,
        showCount: pageSize
      }
    }).then(json => {
      this.setState({ loadingAdvert: false });
      if (json.code === 10000000) {
        const list = json.data.list.map(coin => {
          coin.key = coin.id;
          return coin;
        });
        let advertList = json.data;
        advertList.list = list;
        advertList.price = 0;
        this.setState({ advertList, current });
      } else {
        message.error(json.msg);
      }
    });
  };

  tabOrderChange = key => {
    //登录
    if (sessionStorage.getItem("account")) {
      if (key === "undoOrder") {
        this.setState({ undoOrderList: [] });
        this.getUndoOrderList();
        this.setState({ currentOrderTab: "undoOrder" });
      } else {
        //this.closeOrderInterval();
        if (key === "completedOrder") {
          this.getCompleteOrderList(1);
          this.setState({ completedPage: 1 });
        } else if (key === "cancelledOrder") {
          this.getCancleOrderList(1);
          this.setState({ cancelPage: 1 });
        } else if (key === "advert") {
          this.getMyAdvertList(1);
          this.setState({ advertPage: 1 });
        } else if (key === "appealList") {
          //获取申诉
          this.getAppealList(1);
          this.setState({ appealPage: 1 });
        }
      }
    } else {
      /*  message.destroy();
      message.warn("请先登录"); */
    }
  };

  showModal = visible => {
    this.setState({ [visible]: true });
  };

  hideModal = visible => {
    this.setState({ [visible]: false });
  };

  triggerRelease = () => {
    const { localization } = this.props;
    if (!sessionStorage.getItem("account")) {
      message.info(localization["请先登录"]);
      return;
    }

    //验证是否可以发布广告
    this.request("/offline/topublish", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        //通过验证，可以发广告
        this.hideModal("transactionVisible");
        this.showModal("releaseVisible");
      } else if (json.code === 10004017) {
        //请进行身份认证
        Modal.confirm({
          className: "v-center-modal",
          title: localization["发布广告"],
          content: localization["为保证资金安全，请在交易前实名认证"],
          okText: localization["去实名"],
          cancelText: localization["取消"],
          onOk: () => {
            this.props.history.push("/user/certification");
          }
        });
      } else if (json.code === 10004018) {
        //请先绑定银行卡
        Modal.confirm({
          className: "v-center-modal",
          title: localization["发布广告"],
          content: localization["为保证交易顺畅，请在交易前绑定银行卡"],
          okText: localization["去绑卡"],
          cancelText: localization["取消"],
          onOk: () => {
            this.props.history.push("/user/payment");
          }
        });
      } else if (json.code === 10005036) {
        //请先绑定手机
        Modal.confirm({
          className: "v-center-modal",
          title: localization["发布广告"],
          content: localization["为保证交易顺畅，请在交易前绑定手机号"],
          okText: localization["去绑手机号"],
          cancelText: localization["取消"],
          onOk: () => {
            this.props.history.push("/user/security");
          }
        });
      } else {
        message.destroy();
        message.warn(json.msg, 1);
      }
    });
  };

  //发布广告
  handleRelease = ({ price, volume, exType, minExVolume }) => {
    const { localization } = this.props;
    const { coin } = this.props;
    if (exType === "buy") {
      this.request("/offline/publish", {
        body: {
          volume,
          price,
          exType: 0,
          coinId: coin.coinId,
          symbol: coin.symbol,
          minExVolume
        }
      }).then(json => {
        if (json.code === 10000000) {
          this.hideModal("releaseVisible");
          message.success(localization["发布广告成功！"]);
          //刷新广告列表
          this.getAdvertList(this.state.current);
          //刷新我发布的广告列表
          this.getMyAdvertList(1);
          this.setState({ advertPage: 1 });
        } else {
          message.error(json.msg);
        }
      });
    } else if (exType === "sell") {
      const account = JSON.parse(sessionStorage.getItem("account"));
      if (account.exValidType) {
        this.request("/offline/publish", {
          body: {
            volume,
            price,
            exType: 1,
            coinId: coin.coinId,
            symbol: coin.symbol,
            minExVolume
          }
        }).then(json => {
          if (json.code === 10000000) {
            this.hideModal("releaseVisible");
            message.success(localization["发布广告成功！"]);
            //刷新广告列表
            this.getAdvertList(this.state.current);
            //刷新我发布的广告列表
            this.getMyAdvertList(1);
            this.setState({ advertPage: 1 });
          } else {
            message.error(json.msg);
          }
        });
      } else {
        this.setState({
          payModal: (
            <SettingPopup
              onCancel={() => {
                this.setState({ payModal: "" });
              }}
              onOk={() => {
                this.props.history.push("/user/security");
              }}
            />
          )
        });
      }
    }
  };

  triggerTransaction = ({ exType, record }) => {
    //获取资产
    this.getVolume();
    const { localization } = this.props;
    if (!sessionStorage.getItem("account")) {
      message.info(localization["请先登录"]);
      return;
    }
    this.showModal("transactionVisible");
    this.setState({ selectedCoin: record });
  };

  handleTransaction = ({ price, volume, exType }) => {
    const { localization } = this.props;
    const { selectedCoin } = this.state;
    const typeText = {
      buy: localization["买入"],
      sell: localization["卖出"]
    };

    if (exType === "buy") {
      this.request(`/offline/buy`, {
        body: {
          volume,
          orderId: selectedCoin.id,
          coinId: selectedCoin.coinId,
          symbol: selectedCoin.symbol,
        }
      }).then(json => {
        if (json.code === 10000000) {
          this.hideModal("transactionVisible");
          message.success(
            `${typeText[exType]}${selectedCoin.symbol}${localization["成功"]}`
          );
          this.getUndoOrderList();
          //刷新广告列表
          this.getAdvertList(this.state.current);
        } else if (json.code === 10004016) {
          //自己不能卖给自己
          Modal.error({
            title: typeText[exType],
            content: localization["自己不能卖给自己"],
            okText: localization["确定"]
          });
        } else if (json.code === 10004009) {
          //没有足够资产
          Modal.error({
            title: typeText[exType],
            content: json.msg,
            okText: localization["确定"]
          });
        } else if (json.code === 10004017) {
          //请进行身份认证
          Modal.confirm({
            className: "v-center-modal",
            content: localization["为保证资金安全，请在交易前实名认证"],
            okText: localization["去实名"],
            cancelText: localization["取消"],
            onOk: () => {
              this.props.history.push("/user/certification");
            }
          });
        }else {
          message.error(json.msg);
        }
      });
    } else if (exType === "sell") {
      const account = JSON.parse(sessionStorage.getItem("account"));
      if (account.exValidType) {
        this.request(`/offline/sell`, {
          body: {
            volume,
            orderId: selectedCoin.id,
            coinId: selectedCoin.coinId,
            symbol: selectedCoin.symbol,
          }
        }).then(json => {
          if (json.code === 10000000) {
            this.hideModal("transactionVisible");
            message.success(
              `${typeText[exType]}${selectedCoin.symbol}${localization["成功"]}`
            );
            this.getUndoOrderList();
            //刷新广告列表
            this.getAdvertList(this.state.current);
          } else if (json.code === 10004016) {
            //自己不能卖给自己
            Modal.error({
              title: typeText[exType],
              content: localization["自己不能卖给自己"],
              okText: localization["确定"]
            });
          } else if (json.code === 10004009) {
            //没有足够资产
            Modal.error({
              title: typeText[exType],
              content: json.msg,
              okText: localization["确定"]
            });
          } else if (json.code === 10004017) {
            //请进行身份认证
            if (exType === "sell") {
              Modal.confirm({
                className: "v-center-modal",
                content: localization["为保证资金安全，请在交易前实名认证"],
                okText: localization["去实名"],
                cancelText: localization["取消"],
                onOk: () => {
                  this.props.history.push("/user/certification");
                }
              });
            }
          } else if (json.code === 10004018) {
            //请先绑定银行卡
            if (exType === "sell") {
              Modal.confirm({
                className: "v-center-modal",
                content: localization["为保证交易顺畅，请在交易前绑定银行卡"],
                okText: localization["去绑卡"],
                cancelText: localization["取消"],
                onOk: () => {
                  this.props.history.push("/user/payment");
                }
              });
            }
          } else {
            message.destroy();
            message.error(json.msg);
          }
        });
      } else {
        this.setState({
          payModal: (
            <SettingPopup
              onCancel={() => {
                this.setState({ payModal: "" });
              }}
              onOk={() => {
                this.props.history.push("/user/security");
              }}
            />
          )
        });
      }
    }
  };

  pageAdverstOnChange = page => {
    this.setState({ advertPage: page });
    this.getMyAdvertList(page);
  };

  pageCompletedOnChange = page => {
    this.setState({ completedPage: page });
    this.getCompleteOrderList(page);
  };

  pageCancelOnChange = page => {
    this.setState({ cancelPage: page });
    this.getCancleOrderList(page);
  };

  pageAppealOnChange = page => {
    this.setState({ appealPage: page });
    this.getAppealList(page);
  };

  closeOrderInterval = () => {
    if (this.orderInterval) {
      clearInterval(this.orderInterval);
    }
  };

  openOrderInterval = () => {
    this.orderInterval = setInterval(() => {
      const { undoOrderList } = this.state;
      if (undoOrderList && undoOrderList.length > 0) {
        const myUndoList = undoOrderList.map(item => {
          if (item.remainingTime > 0) {
            item.remainingTime = item.remainingTime - 1;
          }
          return item;
        });
        // console.log(1111);
        this.setState({ undoOrderList: myUndoList });
      }
    }, 1000);
  };

  //获取我的未完成订单列表
  getUndoOrderList = () => {
    //请求之前 先清除定时器
    this.closeOrderInterval();
    this.request("/offline/myOrderDetail/list", {
      method: "POST",
      body: {
        status: 0,
        currentPage: 1,
        showCount: 100
      }
    }).then(json => {
      if (json.code === 10000000) {
        if (json.data.list) {
          const undoOrderList = json.data.list.map(order => {
            order.key = order.id;
            return order;
          });
          //打开定时器 刷新未完成订单
          if (undoOrderList) {
            this.openOrderInterval();
          }
          this.setState({ undoOrderList });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  //获取我的已完成订单
  getCompleteOrderList = page => {
    this.request("/offline/myOrderDetail/list", {
      method: "POST",
      body: {
        status: 2,
        currentPage: page,
        showCount: 10
      }
    }).then(json => {
      if (json.code === 10000000) {
        if (json.data.list) {
          const completedOrderList = json.data.list.map(order => {
            order.key = order.id;
            return order;
          });
          this.setState({
            completedOrderList,
            completedTotal: json.data.count
          });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  //获取已取消订单
  getCancleOrderList = page => {
    this.request("/offline/myOrderDetail/list", {
      method: "POST",
      body: {
        status: 9,
        currentPage: page,
        showCount: 10
      }
    }).then(json => {
      if (json.code === 10000000) {
        if (json.data.list) {
          const cancelledOrderList = json.data.list.map(order => {
            order.key = order.id;
            return order;
          });
          this.setState({ cancelledOrderList, cancelTotal: json.data.count });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  //获取我的广告列表
  getMyAdvertList = page => {
    const { localization } = this.props;
    this.request("/offline/myAdvert/list", {
      method: "POST",
      body: {
        currentPage: page,
        showCount: 10
      }
    }).then(json => {
      if (json.code === 10000000) {
        const typeMap = {
          0: localization["买入"],
          1: localization["卖出"]
        };
        if (json.data.list) {
          const myAdvertList = json.data.list.map(order => {
            order.key = order.id;
            order.exType = typeMap[order.exType];
            return order;
          });
          this.setState({ myAdvertList, advertTotal: json.data.count });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  //根据币种ID获取余额
  getVolume = () => {
    this.request(`/offline/volume/${this.props.coin.coinId}`, {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        if (json.data) {
          this.setState({ coinVolume: json.data.volume });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  handleSwitchRelease = key => {
    if (key === "2") {
      this.getVolume();
    }
  };

  handlePreview = qrcodeId => {
    this.setState({ previewImage: `${IMAGES_ADDRESS}/view/${qrcodeId}` });
  };

  handleCloseImage = () => {
    this.setState({ previewImage: "" });
  };

  //撤销广告
  cancelAdvert = record => {
    const { localization } = this.props;
    this.request("/offline/gadvert/cancel", {
      body: { orderId: record.id }
    }).then(json => {
      if (json.code === 10000000) {
        const { advertPage } = this.state;
        this.getMyAdvertList(advertPage);
        message.success(localization["撤销广告成功！"]);
      } else {
        message.error(json.msg);
      }
    });
  };

  // 撤销申诉
  cancelAppeal = appealId => {
    const { localization } = this.props;
    this.request("/offline/appeal/cancel", {
      method: "POST",
      body: {
        appealId
      }
    }).then(json => {
      if (json.code === 10000000) {
        message.success(localization["撤销申诉成功！"]);
        const { appealPage } = this.state;
        this.getAppealList(appealPage);
      } else {
        message.destroy();
        message.warn(json.msg, 1);
      }
    });
  };

  // 点击撤销申诉
  handleCancel = appealId => {
    this.cancelAppeal(appealId);
  };

  // 获取申诉列表
  getAppealList = page => {
    this.request("/offline/appeal/findall", {
      method: "GET",
      body: {
        currentPage: page,
        showCount: 10
      }
    }).then(json => {
      if (json.code === 10000000) {
        let appealList = [];
        if (json.data.list) {
          appealList = json.data.list.map(item => {
            item.key = item.id;
            return item;
          });
        }
        this.setState({ appealList, appealTotal: json.data.count });
      }
    });
  };

  //资产互转
  transfAssert = () => {
    const account = sessionStorage.getItem("account");
    if (!account) {
      message.destroy();
      message.info("请先登录");

      return;
    }
    const { coin } = this.props;
    const coinProps = {
      coinId: coin.coinId,
      symbol: coin.symbol
    };
    this.setState({
      payModal: (
        <TransfPopup
          {...coinProps}
          onCancel={() => {
            this.setState({ payModal: "" });
          }}
          onOK={() => {
            this.setState({ payModal: "" });
          }}
        />
      )
    });
  };

  closePayModal = () => {
    this.setState({ payModal: "" });
    // 关闭 窗口获取 未完成订单
    this.getUndoOrderList();

    //刷新广告列表
    this.getAdvertList(this.state.current);
  };

  //显示订单详情
  showPayModal = record => {
    this.setState({
      payModal: <PayModal order={record} onCancel={this.closePayModal} />
    });
  };

  render() {
    const { exType, coin, localization } = this.props;
    const typeText = {
      buy: localization["买入"],
      sell: localization["卖出"]
    };

    const {
      coinVolume,
      advertList,
      current,
      pageSize,
      selectedCoin,
      releaseVisible,
      transactionVisible,
      myAdvertList,
      previewImage,
      appealList,
      appealPage,
      appealTotal,
      advertPage,
      advertTotal,
      completedPage,
      completedTotal,
      cancelPage,
      cancelTotal,
      undoOrderList,
      completedOrderList,
      cancelledOrderList,
      loadingAdvert,
      payModal,
      appealModal
    } = this.state;

    const listColumns = [
      {
        title: localization["商家名称"],
        dataIndex: "realName",
        render: (text, record) => {
          return (
            <span
              className={classnames({
                "name-wrap": true,
                online: true
              })}
            >
              {text && text.substr(0, 1)}
            </span>
          );
        }
      },
      {
        title: `${localization["挂单数量"]}(${coin.symbol})`,
        dataIndex: "volume",
        key: "volume"
      },
      {
        title: "限额",
        dataIndex: "successVolume",
        key: "successVolume",
        render: (text, record) => {
          const { volume, lockVolume, successVolume, minExVolume } = record;
          const { pointVolume } = coin;
          const limitVolume = (volume - lockVolume - successVolume).toFixed(
            pointVolume
          );
          return (
            <div>
              {Number(minExVolume).toFixed(pointVolume)}~{limitVolume}
            </div>
          );
        }
      },

      {
        title: `${localization["价格"]}(CNY)`,
        dataIndex: "price",
        render: (text, record) => (
          <span
            className={classnames({
              "price-wrap": true,
              "font-color-green": exType === "buy",
              "font-color-red": exType === "sell"
            })}
          >
            {text}
          </span>
        )
      },
      {
        title: `${localization["金额"]}(CNY)`,
        dataIndex: "totalPrice",
        key: "totalPrice"
      },
      {
        title: localization["支付方式"],
        dataIndex: "wechatNo",
        key: "wechatNo",
        render: (text, record) => {
          return (
            <div className="pay-list-icon">
              {record.cardNo && <i className="iconfont icon-yinhangqia" />}
              {record.alipayNo && <i className="iconfont icon-zhifubao" />}
              {record.wechatNo && <i className="iconfont icon-wxpay" />}
            </div>
          );
        }
      },
      {
        title: localization["操作"],
        dataIndex: "action",
        key: "action",
        render: (text, record) => {
          if (
            Number(record.volume - record.lockVolume - record.successVolume) > 0
          ) {
            return (
              <Button
                type={exType}
                onClick={this.triggerTransaction.bind(this, { exType, record })}
              >
                {typeText[exType]}
              </Button>
            );
          } else {
            return "";
          }
        }
      }
    ];

    const appealColumns = [
      {
        title: localization["订单号"],
        dataIndex: "subOrderId",
        key: "subOrderId"
      },
      {
        title: localization["时间"],
        dataIndex: "createDate",
        key: "createDate",
        render: text => {
          return stampToDate(text * 1);
        }
      },
      {
        title: localization["申诉类型"],
        dataIndex: "appealType",
        key: "appealType"
      },
      {
        title: localization["申诉理由"],
        dataIndex: "reason",
        key: "reason"
      },
      {
        title: localization["操作"],
        dataIndex: "status",
        key: "status",
        render: (text, record) => {
          switch (text) {
            case "1":
              return (
                <Button
                  type="primary"
                  onClick={() => {
                    this.handleCancel(record.id);
                  }}
                  style={{ borderRadius: 4 }}
                >
                  {localization["撤销申诉"]}
                </Button>
              );
            case "2":
              return <div>{localization["客服已处理完"]}</div>;
            case "3":
              return <div>{localization["已撤销"]}</div>;
            default:
              return "";
          }
        }
      }
    ];

    const undoOrderColumns = [
      {
        title: localization["类型"],
        dataIndex: "remarks",
        key: "remarks",
        render: (text, record) => {
          const typeToText = {
            buy: localization["买入"],
            sell: localization["卖出"]
          };
          return `${typeToText[text]} ${record.symbol}`;
        }
      },
      {
        title: localization["订单号"],
        dataIndex: "subOrderId",
        key: "subOrderId"
      },
      {
        title: `${localization["价格"]}(CNY)`,
        dataIndex: "price",
        key: "price"
      },
      {
        title: localization["数量"],
        dataIndex: "volume",
        key: "volume"
      },
      {
        title: `${localization["总额"]}(CNY)`,
        dataIndex: "totalPrice",
        key: "totalPrice"
      },
      {
        title: localization["状态"],
        dataIndex: "status",
        key: "status",
        render: text => {
          let status = "";
          switch (text) {
            case 0:
              status = "已挂单";
              break;
            case 1:
              status = "已付款";
              break;
            case 2:
              status = "确认收到款";
              break;
            case 3:
              status = "确认没收到款";
              break;
            case 4:
              status = "申诉";
              break;
            case 5:
              status = "仲裁结束";
              break;
            case 9:
              status = "取消";
              break;
            default:
              status = "";
          }
          return localization[status];
        }
      },
      // {
      //   title: '对方姓名',
      //   dataIndex: 'name',
      //   key: 'name'
      // },
      {
        title: localization["下单时间"],
        dataIndex: "createDate",
        key: "createDate",
        render: (text, record) => stampToDate(Number(text), "MM-DD hh:mm:ss")
      },
      /*  {
        title: "订单剩余时间",
        dataIndex: "remainingTime",
        key: "remainingTime",
        render: text => {
          if (text > 0) {
            let hour = parseInt(text / 60);
            hour = fixedZero(hour);

            let minute = text % 60;
            minute = fixedZero(minute);
            return (
              <div
                style={{
                  color: "#d4a668",
                  fontSize: "16px",
                  fontWeight: 600,
                  textAlign: "center"
                }}
              >
                {hour} : {minute}
              </div>
            );
          } else {
            return <div style={{ textAlign: "center" }}>--</div>;
          }
        }
      }, */
      {
        title: localization["操作"],
        dataIndex: "action",
        key: "action",
        render: (text, record) => {
          return (
            <div>
              <Button
                type="primary"
                onClick={() => {
                  this.showPayModal(record);
                }}
              >
                订单详情
              </Button>
            </div>
          );
        }
      }
    ];

    const orderColumns = [
      {
        title: localization["类型"],
        dataIndex: "remarks",
        key: "remarks",
        render: (text, record) => {
          const typeToText = {
            buy: localization["买入"],
            sell: localization["卖出"]
          };
          return `${typeToText[text]} ${record.symbol}`;
        }
      },
      {
        title: localization["订单号"],
        dataIndex: "subOrderId",
        key: "subOrderId"
      },
      {
        title: `${localization["价格"]}(CNY)`,
        dataIndex: "price",
        key: "price"
      },
      {
        title: localization["数量"],
        dataIndex: "volume",
        key: "volume"
      },
      {
        title: `${localization["总额"]}(CNY)`,
        dataIndex: "totalPrice",
        key: "totalPrice"
      },
      {
        title: localization["状态"],
        dataIndex: "status",
        key: "status",
        render: text => {
          let status = "";
          switch (text) {
            case 0:
              status = "已挂单";
              break;
            case 1:
              status = "已付款";
              break;
            case 2:
              status = "确认收到款";
              break;
            case 3:
              status = "确认没收到款";
              break;
            case 4:
              status = "申诉";
              break;
            case 5:
              status = "仲裁结束";
              break;
            case 9:
              status = "取消";
              break;
            default:
              status = "";
          }
          return localization[status];
        }
      },
      {
        title: localization["下单时间"],
        dataIndex: "createDate",
        key: "createDate",
        render: (text, record) => stampToDate(Number(text), "MM-DD hh:mm:ss")
      },
      {
        title: localization["操作"],
        dataIndex: "action",
        key: "action",
        render: (text, record) => {
          return (
            <div>
              <Button
                type="primary"
                onClick={() => {
                  this.showPayModal(record);
                }}
              >
                订单详情
              </Button>
            </div>
          );
        }
      }
    ];

    const advertColumns = [
      {
        title: localization["创建时间"],
        dataIndex: "createDate",
        key: "createDate",
        render: (text, record) => stampToDate(Number(text), "MM-DD hh:mm:ss")
      },
      {
        title: localization["类型"],
        dataIndex: "exType",
        key: "exType"
      },
      {
        title: `${localization["价格"]}(CNY)`,
        dataIndex: "price",
        key: "price"
      },
      {
        title: localization["币种"],
        dataIndex: "symbol",
        key: "symbol"
      },
      {
        title: `${localization["挂单数量"]}`,
        dataIndex: "volume",
        key: "volume"
      },
      {
        title: `${localization["成交数量"]}`,
        dataIndex: "successVolume",
        key: "successVolume"
      },
      {
        title: `${localization["锁定数量"]}`,
        dataIndex: "lockVolume",
        key: "lockVolume"
      },
      {
        title: `最小成交数量`,
        dataIndex: "minExVolume",
        key: "minExVolume"
      },

      {
        title: `${localization["总额"]}(CNY)`,
        dataIndex: "totalPrice",
        key: "totalPrice"
      },
      {
        title: localization["状态"],
        dataIndex: "status",
        key: "status",
        render: text => {
          let status = "";
          switch (text) {
            case 0:
              status = "已发布";
              break;
            case 1:
              status = "已完成";
              break;
            case 2:
              status = "部分成交";
              break;
            case 3:
              status = "部分取消";
              break;
            case 9:
              status = "取消";
              break;
            default:
              status = "";
          }

          return localization[status];
        }
      },
      {
        title: localization["操作"],
        dataIndex: "action",
        key: "action",
        render: (text, record) => {
          if (record.status === 0 || record.status === 2) {
            return (
              <Button
                type="primary"
                onClick={this.cancelAdvert.bind(this, record)}
              >
                {localization["撤销广告"]}
              </Button>
            );
          } else {
            return "--";
          }
        }
      }
    ];

    // 买入数量默认值
    let defaultVolum = 0;
    let pointVolume = coin.pointVolume;
    let myMinExVolume = "";

    if (selectedCoin) {
      if (pointVolume === 0) {
        pointVolume = 0;
      } else {
        pointVolume = coin.pointVolume || 4;
      }
      defaultVolum = Number(
        selectedCoin.volume -
        selectedCoin.lockVolume -
        selectedCoin.successVolume
      ).toFixed(pointVolume);

      const { minExVolume } = selectedCoin;

      myMinExVolume =
        minExVolume > 0 ? Number(minExVolume).toFixed(pointVolume) : 0;
    }

    return (
      <div className="trade-cont">
        <div className="trade-list">
          <div className="trade-list-header clear">
            <Button
              type="primary"
              size="large"
              style={{ marginRight: 20 }}
              onClick={this.triggerRelease}
              className="trade-release pull-right"
            >
              <i className="iconfont icon-jia" />
              {localization["发布广告"]}
            </Button>
            <div className="pull-right" style={{ paddingRight: 20 }}>
              <Button type="primary" size="large" onClick={this.transfAssert}>
                {"资产互转"}
              </Button>
            </div>
            <Modal
              title={localization["发布广告"]}
              wrapClassName="c2c-modal v-center-modal"
              visible={releaseVisible}
              onCancel={this.hideModal.bind(this, "releaseVisible")}
              footer={null}
            >
              <Tabs defaultActiveKey="1" onChange={this.handleSwitchRelease}>
                {releaseVisible && [
                  <TabPane
                    tab={`${localization["买入"]}${coin.symbol}`}
                    key="1"
                  >
                    {releaseVisible && (
                      <TransactionForm
                        localization={localization}
                        coin={coin}
                        exType="buy"
                        modalType="adverst"
                        price={advertList && advertList.price}
                        onSubmit={this.handleRelease}
                      />
                    )}
                  </TabPane>,
                  <TabPane
                    tab={`${localization["卖出"]}${coin.symbol}`}
                    key="2"
                  >
                    {releaseVisible && (
                      <TransactionForm
                        localization={localization}
                        coin={coin}
                        exType="sell"
                        modalType="adverst"
                        price={advertList && advertList.price}
                        myProperty={coinVolume}
                        onSubmit={this.handleRelease}
                      />
                    )}
                  </TabPane>
                ]}
              </Tabs>
            </Modal>
          </div>
          <Table
            dataSource={advertList && advertList.list}
            columns={listColumns}
            loading={loadingAdvert}
            pagination={{
              current,
              pageSize,
              total: advertList && advertList.count,
              onChange: this.pageOnChange
            }}
            locale={{
              emptyText: (
                <span>
                  <i className="iconfont icon-zanwushuju" />
                  {localization["暂无数据"]}
                </span>
              )
            }}
          />
        </div>
        <div className="trade-record">
          <Tabs defaultActiveKey="undoOrder" onChange={this.tabOrderChange}>
            <TabPane tab={localization["我的未完成订单"]} key="undoOrder">
              <Table
                dataSource={undoOrderList}
                columns={undoOrderColumns}
                onExpand={this.handleExpand}
                pagination={false}
                locale={{
                  emptyText: (
                    <span>
                      <i className="iconfont icon-zanwushuju" />
                      {localization["暂无数据"]}
                    </span>
                  )
                }}
              />
            </TabPane>
            <TabPane tab={localization["我发布的广告"]} key="advert">
              <Table
                dataSource={myAdvertList}
                columns={advertColumns}
                pagination={{
                  current: advertPage,
                  pageSize: 10,
                  total: advertTotal,
                  onChange: this.pageAdverstOnChange
                }}
                locale={{
                  emptyText: (
                    <span>
                      <i className="iconfont icon-zanwushuju" />
                      {localization["暂无数据"]}
                    </span>
                  )
                }}
              />
            </TabPane>
            <TabPane tab={localization["我的已完成订单"]} key="completedOrder">
              <Table
                dataSource={completedOrderList}
                columns={orderColumns}
                pagination={{
                  current: completedPage,
                  pageSize: 10,
                  total: completedTotal,
                  onChange: this.pageCompletedOnChange
                }}
                locale={{
                  emptyText: (
                    <span>
                      <i className="iconfont icon-zanwushuju" />
                      {localization["暂无数据"]}
                    </span>
                  )
                }}
              />
            </TabPane>
            <TabPane tab={localization["我的已取消订单"]} key="cancelledOrder">
              <Table
                dataSource={cancelledOrderList}
                columns={orderColumns}
                pagination={{
                  current: cancelPage,
                  pageSize: 10,
                  total: cancelTotal,
                  onChange: this.pageCancelOnChange
                }}
                locale={{
                  emptyText: (
                    <span>
                      <i className="iconfont icon-zanwushuju" />
                      {localization["暂无数据"]}
                    </span>
                  )
                }}
              />
            </TabPane>
            <TabPane tab={localization["我的申诉"]} key="appealList">
              <Table
                dataSource={appealList}
                columns={appealColumns}
                pagination={{
                  current: appealPage,
                  pageSize: 10,
                  total: appealTotal,
                  onChange: this.pageAppealOnChange
                }}
                locale={{
                  emptyText: (
                    <span>
                      <i className="iconfont icon-zanwushuju" />
                      {localization["暂无数据"]}
                    </span>
                  )
                }}
              />
            </TabPane>
          </Tabs>
        </div>
        <Modal
          title={`${typeText[exType]} ${coin.symbol}`}
          wrapClassName="c2c-modal v-center-modal"
          visible={transactionVisible}
          onCancel={this.hideModal.bind(this, "transactionVisible")}
          footer={null}
        >
          {transactionVisible && (
            <TransactionForm
              localization={localization}
              freezePrice
              coin={coin}
              modalType="trade"
              exType={exType}
              myProperty={coinVolume}
              price={selectedCoin.price}
              minExVolume={myMinExVolume}
              maxLimitVolume={defaultVolum}
              onSubmit={this.handleTransaction}
            />
          )}
        </Modal>
        {payModal}
        {appealModal}
      </div>
    );
  }
}

export default withRouter(TradeContainer);
